package com.itheima.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.SetmealDto;
import com.itheima.exeption.CustomException;
import com.itheima.mapper.SetmealDishMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

@Resource
private SetmealMapper setmealMapper;
@Resource
private SetmealDishService setmealDishService;

private SetmealDishMapper setSetmealDishMapper;
    @Override
    public int addSetmeal(SetmealDto setmealDto) {
        int insert = setmealMapper.insert(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        setmealDishes.stream().map(item->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

setmealDishService.saveBatch(setmealDishes);

        return insert;
    }

    @Override
    public boolean deleteSetmeal(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> sw = new LambdaQueryWrapper<>();
        sw.in(Setmeal ::getId,ids);
        sw.eq(Setmeal ::getStatus,1);
        Integer count = setmealMapper.selectCount(sw);

        if (count == 1) {
           return false;
        }

        setmealMapper.delete(sw);

        LambdaQueryWrapper<SetmealDish> sd = new LambdaQueryWrapper<>();
        sd.eq(SetmealDish::getSetmealId,ids);
        boolean remove = setmealDishService.remove(sd);

        return remove;
    }

    @Override
    public boolean updateSetment(SetmealDto setmealDto) {
        int i = setmealMapper.updateById(setmealDto);

        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish ::getSetmealId,setmealDto.getId());
        setmealDishService.remove(qw);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) ->{
        item.setSetmealId(setmealDto.getId());
        return item;
        }).collect(Collectors.toList());


        boolean b = setmealDishService.saveBatch(setmealDishes);

        return b ;
    }


}
